package com.project.rfidpage.controller;


import com.github.pagehelper.PageInfo;
import com.project.rfidpage.aop.TagLog;
import com.project.rfidpage.dto.BgParam;
import com.project.rfidpage.entity.Bg;
import com.project.rfidpage.service.BgService;
import com.project.rfidpage.util.RestResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/api/rfidpage/bg/")
public class BgController extends BaseController {

    @Resource
    BgService bgService;

    /**
     * 列表查询
     */
    @PostMapping("page")
    @TagLog(operation = 0, content = "查询基站列表")
    public RestResult page(@RequestBody BgParam param) {
        this.getPage(true, param);
        return RestResult.ok(new PageInfo<>(bgService.getListForPage(param)));
    }

    /**
     * 导出列表
     */
    @PostMapping("output")
    @TagLog(operation = 5, content = "导出基站列表")
    public RestResult output(@RequestBody BgParam param) {
        this.getPage(false, param);
        return RestResult.ok(bgService.getListForPage(param));
    }

    /**
     * 检查基站号
     */
    @PostMapping("check")
    @TagLog(operation = 0, content = "检查基站号")
    public RestResult check(@RequestBody BgParam param) {
        List<Bg> list = bgService.getByBgNo(param.getBgno());
        if (list.size() == 0) {
            return RestResult.ok("基站号可用");
        } else {
            return RestResult.error("基站号已经存在");
        }
    }

    /**
     * 新增基站
     */
    @PutMapping("add")
    @TagLog(operation = 2, content = "新增基站")
    public RestResult add(@RequestHeader(value = "user") String user, @RequestBody Bg param) {
        List<Bg> list = bgService.getByBgNo(param.getBgno());
        if (list.size() == 0) {
            try {
                param.setUsername(user);
                param.setRid_vender_regnum(param.getBgno().substring(0, 2));
                param.setInputdt(new Date());
                bgService.insert(param);
                return RestResult.ok();
            } catch (Exception e) {
                return RestResult.error(e.getMessage());
            }
        } else {
            return RestResult.error("基站号已经存在");
        }
    }

    /**
     * 更新基站
     */
    @PutMapping("update")
    @TagLog(operation = 3, content = "更新基站")
    public RestResult update(@RequestHeader(value = "user") String user, @RequestBody Bg param) {
        List<Bg> list = bgService.getByBgNo(param.getBgno());
        if (list.size() == 0) {
            return RestResult.error("该条数据不存在");
        } else {
            try {
                param.setUsername(user);
                param.setRid_vender_regnum(param.getBgno().substring(0, 2));
                param.setInputdt(new Date());
                bgService.update(param, list.get(0).getBgno());
                return RestResult.ok();
            } catch (Exception e) {
                return RestResult.error(e.getMessage());
            }
        }
    }
}
